<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前后端连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .test-button {
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .test-button:hover {
            background: #66b1ff;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
        }
        .success {
            background: #f0f9ff;
            border: 1px solid #67c23a;
            color: #67c23a;
        }
        .error {
            background: #fef0f0;
            border: 1px solid #f56c6c;
            color: #f56c6c;
        }
        .info {
            background: #f4f4f5;
            border: 1px solid #909399;
            color: #606266;
        }
    </style>
</head>
<body>
    <h1>🔧 前后端连接测试工具</h1>
    
    <div class="test-container">
        <h2>📊 服务状态检查</h2>
        <button class="test-button" onclick="checkBackendStatus()">检查后端状态 (9090)</button>
        <button class="test-button" onclick="checkFrontendStatus()">检查前端状态 (8081)</button>
        <div id="statusResult" class="result info">点击按钮检查服务状态...</div>
    </div>

    <div class="test-container">
        <h2>🔗 API连接测试</h2>
        <button class="test-button" onclick="testRolesAPI()">测试角色API</button>
        <button class="test-button" onclick="testLoginAPI()">测试登录API</button>
        <button class="test-button" onclick="testCORS()">测试CORS</button>
        <div id="apiResult" class="result info">点击按钮测试API连接...</div>
    </div>

    <div class="test-container">
        <h2>🌐 网络诊断</h2>
        <button class="test-button" onclick="testNetwork()">网络诊断</button>
        <div id="networkResult" class="result info">点击按钮进行网络诊断...</div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:9090/api';
        
        function updateResult(elementId, content, type = 'info') {
            const element = document.getElementById(elementId);
            element.textContent = content;
            element.className = `result ${type}`;
        }

        async function checkBackendStatus() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/roles`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    updateResult('statusResult', 
                        `✅ 后端服务正常 (9090端口)\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`, 
                        'success'
                    );
                } else {
                    updateResult('statusResult', 
                        `❌ 后端服务异常\n` +
                        `状态码: ${response.status}\n` +
                        `状态文本: ${response.statusText}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('statusResult', 
                    `❌ 后端连接失败\n` +
                    `错误信息: ${error.message}\n` +
                    `可能原因: 后端服务未启动或端口被占用`, 
                    'error'
                );
            }
        }

        async function checkFrontendStatus() {
            try {
                const response = await fetch('http://localhost:8081', {
                    method: 'GET'
                });
                
                if (response.ok) {
                    updateResult('statusResult', 
                        `✅ 前端服务正常 (8081端口)\n` +
                        `状态码: ${response.status}\n` +
                        `服务地址: http://localhost:8081`, 
                        'success'
                    );
                } else {
                    updateResult('statusResult', 
                        `❌ 前端服务异常\n` +
                        `状态码: ${response.status}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('statusResult', 
                    `❌ 前端连接失败\n` +
                    `错误信息: ${error.message}\n` +
                    `可能原因: 前端服务未启动`, 
                    'error'
                );
            }
        }

        async function testRolesAPI() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/roles`);
                const data = await response.json();
                
                updateResult('apiResult', 
                    `✅ 角色API测试成功\n` +
                    `URL: ${API_BASE_URL}/auth/roles\n` +
                    `状态码: ${response.status}\n` +
                    `响应数据: ${JSON.stringify(data, null, 2)}`, 
                    'success'
                );
            } catch (error) {
                updateResult('apiResult', 
                    `❌ 角色API测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        async function testLoginAPI() {
            try {
                const loginData = {
                    username: 'admin',
                    password: 'admin123'
                };
                
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(loginData)
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    updateResult('apiResult', 
                        `✅ 登录API测试成功\n` +
                        `URL: ${API_BASE_URL}/auth/login\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`, 
                        'success'
                    );
                } else {
                    updateResult('apiResult', 
                        `❌ 登录API测试失败\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.message || '未知错误'}`, 
                        'error'
                    );
                }
            } catch (error) {
                updateResult('apiResult', 
                    `❌ 登录API测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        async function testCORS() {
            try {
                const response = await fetch(`${API_BASE_URL}/auth/roles`, {
                    method: 'OPTIONS',
                    headers: {
                        'Origin': 'http://localhost:8081',
                        'Access-Control-Request-Method': 'GET',
                        'Access-Control-Request-Headers': 'Content-Type'
                    }
                });
                
                const corsHeaders = {
                    'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
                    'Access-Control-Allow-Methods': response.headers.get('Access-Control-Allow-Methods'),
                    'Access-Control-Allow-Headers': response.headers.get('Access-Control-Allow-Headers')
                };
                
                updateResult('apiResult', 
                    `✅ CORS测试完成\n` +
                    `状态码: ${response.status}\n` +
                    `CORS头信息: ${JSON.stringify(corsHeaders, null, 2)}`, 
                    'success'
                );
            } catch (error) {
                updateResult('apiResult', 
                    `❌ CORS测试失败\n` +
                    `错误信息: ${error.message}`, 
                    'error'
                );
            }
        }

        async function testNetwork() {
            const results = [];
            
            // 测试DNS解析
            try {
                const response = await fetch('http://localhost:9090/api/auth/roles');
                results.push(`✅ DNS解析正常`);
            } catch (error) {
                results.push(`❌ DNS解析失败: ${error.message}`);
            }
            
            // 测试端口连通性
            try {
                const response = await fetch('http://localhost:9090/api/auth/roles');
                results.push(`✅ 端口9090连通正常`);
            } catch (error) {
                results.push(`❌ 端口9090连通失败: ${error.message}`);
            }
            
            // 测试HTTPS重定向
            try {
                const response = await fetch('https://localhost:9090/api/auth/roles');
                results.push(`✅ HTTPS重定向正常`);
            } catch (error) {
                results.push(`⚠️ HTTPS重定向失败 (正常): ${error.message}`);
            }
            
            updateResult('networkResult', 
                `🌐 网络诊断结果:\n${results.join('\n')}`, 
                'info'
            );
        }

        // 页面加载时自动检查
        window.onload = function() {
            checkBackendStatus();
        };
    </script>
</body>
</html>